import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import * as moment from 'moment';
import {ActivatedRoute, Router} from "@angular/router";
import {tuikeSystemUrl} from "../../../../config/api";
import {Headers, RequestOptions} from "@angular/http";
import {HttpService} from "../../../lib/service/http.service";

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {
  validateForm: FormGroup;
  start_date = null;
  end_date = null;
  send_time = null;
  activity_id;
  active_type;
  active_template_id;
  activity_type = [];
  template_list = [];
  keyWordList;
  exampleList;
  keyWord;
  addStatus = false;
  isShow = false;
  message = '';
  type = '';
  pushId = null;
  promise = null;
  cacheTemplateId = null;
  status = false;
  readonly = false;
  page = null;
  active_template_name = '';

  constructor(private fb: FormBuilder, private router: Router, private route: ActivatedRoute, private httpService: HttpService
  ) {
  }

  ngOnInit() {
    this.activity_id = +this.route.snapshot.queryParams['id'];
    this.route.snapshot.queryParams['readonly'] ? this.readonly = true : this.readonly = false;
    this.route.snapshot.queryParams['page'] ? this.page = this.route.snapshot.queryParams['page'] : this.page = null;
    this.initInfo(this.activity_id);
    this.validateForm = this.fb.group({
      'title': ['', [Validators.required]],
      'send_time': [null, [Validators.required]],
      'template_id': [null, [Validators.required]],
      'type': [null, [Validators.required]],
      'remark': [null, [Validators.required]],
      'activity_id': [null, [Validators.required]],
      // 'page': ['', [Validators.required]],
    });
    let date = new Date();
    let min = date.getMinutes();
    date.setMinutes(min + 2);
    this.validateForm.controls['send_time'].setValue(new Date(moment(date.getTime()).format('YYYY-MM-DD HH:mm:ss')));
    this.validateForm.controls['activity_id'].patchValue(this.activity_id);
    this.promise = new Promise((resolve, reject) => {
      this.getTemplateList(1).subscribe(res => {
        if (res.code === 200) {
          this.template_list = res.data;
          this.active_template_id = this.template_list[0]['template_id'];
          this.active_template_name = this.template_list[0]['title'];
          this.validateForm.controls['template_id'].patchValue(this.active_template_id);
          this.keyWordList = this.template_list[0]['content'].match(/[\u4e00-\u9fa5]+/g);
          this.exampleList = this.template_list[0]['example'].match(/.*\n/g);

          for (let i = 10; i > 0; i--) {
            this.validateForm.removeControl('keyword' + i);
          }
          this.keyWordList.map((e, i) => {
            this.validateForm.addControl('keyword' + (i + 1), this.fb.control('', [Validators.required]));
          });
          resolve('success');
        }
      });
    });
    if (this.route.snapshot.queryParams['pushId']) {
      this.pushId = +this.route.snapshot.queryParams['pushId'];
      this.getInfo(this.pushId).subscribe(res => {
        if (res.code === 200) {
          let data = res.data;
          let keyword = JSON.parse(data.content).data;
          this.validateForm.controls['send_time'].setValue(new Date(data.send_time));
          this.validateForm.controls['title'].setValue(data.title);
          // this.validateForm.controls['template_id'].setValue(data.template_id);
          this.validateForm.controls['remark'].setValue(data.remark);
          this.validateForm.controls['type'].setValue(data.type);
          this.validateForm.controls['activity_id'].setValue(data.activity_id);
          // this.validateForm.controls['page'].setValue(JSON.parse(data.content).page);
          this.cacheTemplateId = data.template_id;
          this.promise.then(res => {
            this.active_template_id = data.template_id;
            this.template_list.map((e1, i1) => {
              if (e1['template_id'] == this.active_template_id) {
                this.active_template_name = this.template_list[i1]['title'];
                this.keyWordList = this.template_list[i1]['content'].match(/[\u4e00-\u9fa5]+/g);
                this.exampleList = this.template_list[i1]['example'].match(/.*\n/g);
                for (let i = 10; i > 0; i--) {
                  this.validateForm.removeControl('keyword' + i);
                }
                for (let k in keyword) {
                  this.validateForm.addControl(k, this.fb.control(keyword[k]['value'], [Validators.required]));
                }
              }
            });
          })
        }
      })
    }
  }

  //初始化页面数据
  initInfo(activity_id) {
    const url = `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/send_index`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({'activity_id': activity_id});
    this.httpService.httpPostAuth(url, body, options).subscribe(res => {
      if (res.code === 200) {
        if (this.activity_type.length === 0) {
          for (var key in res.data.type) {
            this.activity_type.push({
              label: res.data.type[key],
              value: key
            });
            if (key == res.data.activity.type) {
              this.active_type = key;
              this.validateForm.controls['type'].patchValue(this.active_type);
            }
          }
        }
      }
    })
  }

  //获取指定信息
  getInfo(id) {
    const url = `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/info_message?id=${id}`;
    return this.httpService.httpGetAuth(url).map(res => res);
  }

  selectTemplate(e) {
    if (this.cacheTemplateId == e) {
      return;
    }
    this.template_list.map((e1, i1) => {
      if (e1['template_id'] == e) {
        this.active_template_name = this.template_list[i1]['title'];
        this.keyWordList = this.template_list[i1]['content'].match(/[\u4e00-\u9fa5]+/g);
        this.exampleList = this.template_list[i1]['example'].match(/.*\n/g);
        for (let i = 10; i > 0; i--) {
          this.validateForm.removeControl('keyword' + i);
        }
        this.keyWordList.map((e2, i2) => {
          this.validateForm.addControl('keyword' + (i2 + 1), this.fb.control('', [Validators.required]));
        });
      }
    });
    this.cacheTemplateId = e;
  }

  //获取模板列表
  getTemplateList(page) {
    const url = `${tuikeSystemUrl}/api/v1/admin/wechat_message_template/my_template_list`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({'page': page, 'pageSize': 10});
    return this. httpService.httpPostAuth(url, body, options).map(res => res);
  }


  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  };


  _startValueChange = () => {
    if (this.start_date > this.end_date) {
      this.end_date = null;
    }
  }
  _endValueChange = () => {
    if (this.start_date > this.end_date) {
      this.start_date = null;
    }
  }
  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.validateForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.validateForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }
  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this.start_date) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this.start_date.getTime();
  }

  get _isSameDay() {
    return this.start_date && this.end_date && moment(this.start_date).isSame(this.end_date, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.start_date.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.start_date.getHours()) {
          return this.newArray(this.start_date.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.start_date.getHours() && m === this.start_date.getMinutes()) {
          return this.newArray(this.start_date.getSeconds());
        }
        return [];
      }
    };
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    const value = this.validateForm.value;
    if (this.validateForm.valid) {
      this.addStatus = true;
      const data = {};
      data['keyword'] = [];
      for (let k in value) {
        if (/^keyword{1,2}/g.test(k)) {
          data['keyword'].push(this.validateForm.controls[k].value);
        };
      };
      data['title'] = this.validateForm.controls['title'].value;
      data['send_time'] = moment(this.validateForm.controls['send_time'].value).format('YYYY-MM-DD HH:mm:ss');
      data['template_id'] = this.active_template_id;
      data['type'] = this.validateForm.controls['type'].value;
      data['remark'] = this.validateForm.controls['remark'].value;
      data['activity_id'] = this.validateForm.controls['activity_id'].value;
      if (this.pushId) {
        data['id'] = this.pushId;
        data['status'] = this.status ? 4 : 1;
      }
      this.addPush(data).subscribe(res => {
        if (res.code === 200) {
          this.message = this.pushId ? '修改成功' : '添加成功';
          this.type = 'success';
          this.isShow = true;
          this.router.navigate(['tuike/discovery/push']);
          this.addStatus = false;
        } else {
          this.message = res.message;
          this.type = 'error';
          this.isShow = true;
          this.addStatus = false;
        }
      })
    }
  }

  addPush(data) {
    const url = this.pushId ? `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/edit_message` : `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/add_message`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify(data);
    return this.httpService.httpPostAuth(url, body, options).map(res => res);
  }

  goBack() {
    if(this.pushId) {
      this.router.navigate(['tuike/discovery/push'],{
        queryParams:{
          page:this.page || 1
        }
      });
    } else {
      this.router.navigate(['tuike/discovery/list']);
    }
  }

  // goBack1() {
  //   this.router.navigate(['tuike/discovery/list']);
  // }


}
